package com.lk.mi.controller;

import com.lk.mi.entity.User;
import com.lk.mi.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private userService userService;

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public String login(String username, String password, Model model, HttpSession session){
        User user = userService.login(username, password);
        //登录成功
        if (user!=null){
            session.setAttribute("SESSION_USERNAME",username);
            Integer id = user.getId();
            session.setAttribute("SESSION_USERID",id);
            Integer level = user.getLevel();
            if (level==1){
                session.setAttribute("SESSION_USERLEVEL",true);
            }else {
                session.setAttribute("SESSION_USERLEVEL",false);
            }

            return "/item/findAll";
        }
        //登录失败
        model.addAttribute("LOGIN_MSG","账号密码错误");
        return "/pages/login.jsp";
    }


    /**
     * 退出登录
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("SESSION_LOGIN");
        return "redirect:/pages/login.jsp";
    }

    /**
     * 注册
     * @param username
     * @param password
     * @param model
     * @return
     */
    @RequestMapping("/register")
    public String register(String username, String password,Model model){
        Integer row = userService.register(username, password);
        //注册成功
        if (row!=null){
            model.addAttribute("LOGIN_MSG","注册成功,请登录");
            return "/pages/login.jsp";
        }
        //注册失败
        model.addAttribute("REGISTER_MSG","注册失败");
        return "/pages/register.jsp";
    }

    /**
     * 注销
     * @param id
     * @return
     */
    @RequestMapping("/destroy")
    public String destroy(Integer id){

        userService.destroy(id);

        return null;
    }

}
